#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2018/1/13 0013 19:37
# @Author  : Arliki
# @File    : distribut_2.py
import time  # not important
import queue
from multiprocessing.managers import BaseManager


# →→→!!{必须以入口文件启动}!!←←←

# 继承BaseManager
class Workers(BaseManager):
    pass


def run():
    # 从网络上获取queue 所以只写名称
    Workers.register('get_send_queue')
    Workers.register('get_receive_queue')
    # 链接服务器
    server_addr = '127.0.0.1'
    print('connect to server %s...' % server_addr)
    # 端口和验证码要一致 链接
    worker = Workers(address=(server_addr, 8888), authkey=b'abcd')
    worker.connect()

    # 获取queue对象
    send = worker.get_send_queue()
    receive = worker.get_receive_queue()
    # 从send队列读取任务并写入receive
    for i in range(200):
        try:
            n = send.get(timeout=5)
            print('run send %d * %d...' % (n, n))
            r = '%d * %d = %d' % (n, n, n * n)
            time.sleep(1)
            receive.put(r)
        except queue.Empty:
            receive.put('send is empty')
            print('send queue is empty')
            exit()
    print('worker exit')


if __name__ == '__main__':
    run()
